<?php

namespace App\Service\CacheService;
use App\Service\BaseService;

/**
 * cache service provider
 * @author chenshubo
 */
class CacheProviderService extends BaseService
{
    /**
     * query hashList
     * @param string $hashName
     * @param $hashField
     * @return mixed
     */
    public static function getCacheByHashList(string $hashName,$needHashField = null)
    {
        try {
            if( is_array($needHashField) ) {
                $hashField  = md5(json_encode($needHashField,JSON_UNESCAPED_UNICODE));
            } else {
                $hashField  = md5($needHashField);
            }
            $redis = redis();
            $cacheJsonValue = $redis->HGET($hashName,$hashField);
            return @json_decode($cacheJsonValue,true);
        } catch ( \Throwable $th) {
            logger('error','redis_error')->info($th->getMessage());
            return false;
        }
    }
    
    /**
     * write hashList
     * @param string $hashName
     * @param $needHashField
     * @param array $cacheData
     * @return mixed
     */
    public static function cacheByHashList(string $hashName,$needHashField,array $cacheHashData = [])
    {
        try {
            
            $hashCacheString = json_encode($cacheHashData,JSON_UNESCAPED_UNICODE);
            if( is_array($needHashField) ) {
                $hashField  = md5(json_encode($needHashField,JSON_UNESCAPED_UNICODE));
            } else {
                $hashField  = md5($needHashField);
            }
            $redis = redis();
            return $redis->HSET($hashName,$hashField,$hashCacheString);
        } catch ( \Throwable $th) {
            logger('error','redis_error')->info($th->getMessage());
            return false;
        }
    }
    
    /**
     * query k/v
     * @param string $key
     * @param array $value
     * @param int $expire
     * @param int $select_db_num
     */
    public static function getCacheByKey(string $key)
    {
        try {
            $redis = redis();
            $redis->select($select_db_num);
            $v = $redis->get($key);
            return @json_decode($v,true);
        } catch ( \Throwable $th) {
            logger('error','redis_error')->info($th->getMessage());
            return false;
        }
    }
    
    /**
     * write set k/v
     * @param string $key
     * @param array $value
     * @param int $expire
     * @param int $select_db_num
     */
    public static function cacheBySetKeyValue(string $key,array $value,int $expire = self::CACHE_TIME,int $select_db_num = 0)
    {
        try {
            $redis = redis();
            $redis->select($select_db_num);
            return $redis->set($key,json_encode($value),$expire);
        } catch ( \Throwable $th) {
            logger('error','redis_error')->info($th->getMessage());
            return false;
        }
    }
}